package com.iqiyi.pps.epg.core.service.sginal;

import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.sginal.TVersionController;
import com.iqiyi.pps.epg.api.model.web.sginal.TVersionControllerDataPage;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.dao.channel.ChannelConfigDao;
import com.iqiyi.pps.epg.core.dao.sginal.VersionControllerDataDao;
import com.iqiyi.pps.epg.core.model.sginal.Server;
import com.iqiyi.pps.epg.core.model.sginal.VersionController;
import com.iqiyi.pps.epg.core.utils.DateTimeUtil;
import com.iqiyi.pps.epg.core.utils.TransUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by yanchao_sx on 2018/1/5.
 */
@Service
@Transactional
public class VersionControllerServiceImpl implements VersionControllerService {

    @Autowired
    private VersionControllerDataDao versionDao;

    @Autowired
    private ChannelConfigDao channelConfigDao;

    @Override
    public VersionController getVersionController(int id) {
        return versionDao.get(id);
    }

    @Override
    public VersionController getVersionControllerByServerID(int serverId) {
        return versionDao.findUniqueBy("serverId",serverId);
    }

    @Override
    public void deleteVersionController(VersionController entity) {
        versionDao.delete(entity);

    }

    @Override
    public List<VersionController> getAll() {
        return versionDao.getAll();
    }

    @Override
    public VersionController string2VersionController(int serverId, String info, String mainVersion) {
        String[] versions = info.split("\\|");
        VersionController versionController = new VersionController(serverId,VersionController.SERVICE_API_ABNORMAL);
        if(versions.length==VersionController.VERSION_NUM){
            int flag = 0;
            String[] mVersions = mainVersion.split(",");
            for(int i=0;i<VersionController.VERSION_NUM;i++){
                if(!versions[i].equals(mVersions[i])){
                    flag=1;
                    break;
                }
            }
            versionController.setZzdVersion(versions[VersionController.ZZD_VERSION_IND-3].equals("") ? null:versions[VersionController.ZZD_VERSION_IND-3]);
            versionController.setEncoderVersion(versions[VersionController.ENCODER_VERSION_IND-3] .equals("") ? null:versions[VersionController.ENCODER_VERSION_IND-3]);
            versionController.setMergeToolVersion(versions[VersionController.MERGE_TOOL_VERSION_IND-3] .equals("") ? null:versions[VersionController.MERGE_TOOL_VERSION_IND-3]);
            versionController.setMergeServiceVersion(versions[VersionController.MERGE_SERVICE_VERSION_IND-3] .equals("") ? null:versions[VersionController.MERGE_SERVICE_VERSION_IND-3]);
            versionController.setPrecisionCutToolVersion(versions[VersionController.PRECISION_CUT_TOOL_VERSION_IND-3] .equals("") ? null:versions[VersionController.PRECISION_CUT_TOOL_VERSION_IND-3]);
            if(flag==0) versionController.setServerStatus(VersionController.SERVICE_NORMAL);
            else versionController.setServerStatus(VersionController.DIFFERENT_VERSION);
        }
        return versionController;
    }

    @Override
    public void insertOrUpdate(VersionController entity) {
        versionDao.save(entity);
    }

    @Override
    public TVersionControllerDataPage getVersionControllerData(TPage page, TFilter filter) {
        Map<String, String> map = filter.getFilters();
        String tempPattern = "${PARAMS}";
        String totalPattern = "select COUNT(*)";
        String tablePattern = " from VersionController version  , Server server where version.serverId = server.id and server.serverType = "+ VersionController.ZZD_TYPE + " and server.status !=" + Server.STATUS_IS_DELETE;
        //String tablePattern =  "from com.iqiyi.pps.epg.core.model.sginal.VersionController version , com.iqiyi.pps.epg.core.model.sginal.Server server where version.serverId = server.id";

        String resultPattern = "select version.serverId,version.zzdVersion,version.encoderVersion,version.mergeServiceVersion,version.mergeToolVersion,version.precisionCutToolVersion,"+
                "version.serverStatus,version.updateTime,server.insideServerIp,server.outsideServerIp,server.hardware,version.id,server.remark,server.status";
        List<PropertyFilter> filterList = TransUtil.builderFilterList(filter);
        String hql =tempPattern + tablePattern;
        page.setOrderBy("version.serverId");
        page.setOrder("desc");
        Page dbPage = TransUtil.buildPage(page);

        hql = TransUtil.buildQueryStringByPropertyFilter(dbPage, hql, filterList);

        if (dbPage.isAutoCount()) {
            String totalCount = versionDao.getSession().createQuery(hql.replace(tempPattern, totalPattern)).uniqueResult().toString();
            page.setTotalCount(Long.valueOf(totalCount));
        }

        hql = TransUtil.buildQueryStringByPropertyFilter(dbPage, resultPattern+tablePattern, filterList);
        List result = versionDao.getSession().createQuery(hql)
                .setMaxResults(dbPage.getPageSize())
                .setFirstResult((dbPage.getPageNo() - 1) * dbPage.getPageSize())
                .list();
        TVersionControllerDataPage tVersionControllerDataPage = new TVersionControllerDataPage();
        tVersionControllerDataPage.setTPage(page);
        List<TVersionController> tVersionControllerDatas = new ArrayList<TVersionController>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(Object single : result) {
            Object[] obj = (Object[]) single;
            VersionController version = new VersionController();
            version.setId(Integer.valueOf(""+obj[11]));
            version.setServerId(Integer.valueOf(""+obj[0]));
            version.setInsideServerIp(""+obj[8]);
            version.setOutsideIp(""+obj[9]);

            version.setZzdVersion(obj[1]==null?"":""+obj[1]);
            version.setEncoderVersion(obj[2]==null?"":""+obj[2]);
            version.setMergeToolVersion(obj[3]==null?"":""+obj[4]);
            version.setMergeServiceVersion(obj[4]==null?"":""+obj[3]);
            version.setPrecisionCutToolVersion(obj[5]==null?"":""+obj[5]);

            version.setUpdateTime(new Timestamp(DateTimeUtil.parseLongFormat(sdf.format(obj[7]))));
            version.setServerStatus(Integer.valueOf(""+obj[6]));
            version.setHardware(""+obj[10]);
            version.setRemark(""+obj[12]);
            version.setStatus(Integer.valueOf(""+obj[13]));

            tVersionControllerDatas.add(version.convertThriftModel());
        }
        tVersionControllerDataPage.setResult(tVersionControllerDatas);
        return tVersionControllerDataPage;
    }

    @Override
    public List<String> getVersionHistory() {
        String[] hqls = new String[VersionController.VERSION_NUM+3];
        List<String> history = new ArrayList<String>();
        String prefix = "select distinct ";
        String pattern = " from VersionController version,Server server where server.id = version.serverId and server.serverType = "+ VersionController.ZZD_TYPE + " and server.status !=" + Server.STATUS_IS_DELETE+" order by ";
        String postfix =" desc";
        hqls[VersionController.ZZD_VERSION_IND] = prefix+ VersionController.ZZD_VERSION + pattern + VersionController.ZZD_VERSION;
        hqls[VersionController.ENCODER_VERSION_IND] = prefix+ VersionController.ENCODER_VERSION + pattern + VersionController.ENCODER_VERSION;
        hqls[VersionController.MERGE_SERVICE_VERSION_IND] = prefix+ VersionController.MERGE_SERVICE_VERSION + pattern + VersionController.MERGE_SERVICE_VERSION;
        hqls[VersionController.MERGE_TOOL_VERSION_IND] = prefix+ VersionController.MERGE_TOOL_VERSION + pattern + VersionController.MERGE_TOOL_VERSION;
        hqls[VersionController.PRECISION_CUT_TOOL_VERSION_IND] = prefix+ VersionController.PRECISION_CUT_TOOL_VERSION + pattern + VersionController.PRECISION_CUT_TOOL_VERSION;
        hqls[VersionController.HARDWARE_IND] = prefix + VersionController.HARDWARE + pattern + VersionController.HARDWARE;
        hqls[VersionController.SERVERSTATUS_IND] = prefix + VersionController.SERVERSTATUS + pattern + VersionController.SERVERSTATUS;
        hqls[VersionController.VERSIONSTATUS_IND] = prefix + VersionController.VERSIONSTATUS + pattern + VersionController.VERSIONSTATUS;
        Session session = versionDao.getSession();

        for (String hql : hqls){
            hql+=postfix;
            List list = session.createQuery(hql).list();
            StringBuffer sb = new StringBuffer();
            for(int i=0;i<list.size();i++){
                sb.append(list.get(i)).append(",");
            }

            history.add(sb.substring(0,sb.lastIndexOf(",")));
        }
        return history;
    }

    @Override
    public List<VersionController> getNewAll() {
        return null;
    }

    @Override
    public String getMainVersion() {
        String hql = "select val from ChannelConfig where type='"+VersionController.CHANNEL_CONFIG_TYPE+"' order by key asc";
        Session session = channelConfigDao.getSession();
        List<String> list = session.createQuery(hql).list();
        StringBuffer sb = new StringBuffer();
        for(String l : list){
            sb.append(l).append(",");
        }
        String versionList = sb.toString();
        return versionList.substring( 0,versionList.lastIndexOf(",") );
    }

    @Override
    public int setMainVersion(String versions) {
        String[] version = versions.split(",");
        Session session = channelConfigDao.getSession();
        if(version.length!=VersionController.VERSION_NUM){
            return -1;
        }
        String prefix = "update ChannelConfig ch set ch.val='";
        String postfix="' where ch.type='"+VersionController.CHANNEL_CONFIG_TYPE+"' and ch.key =";
        for(int i=0;i<VersionController.VERSION_NUM;i++){
            String hql = prefix + version[i]+ postfix + i;
            Query query = session.createQuery(hql);
            query.executeUpdate();
        }

        return 1;
    }

    @Override
    public int synVersionStatus(String versions) {
        List<VersionController> versionList = getAll();
        String[] mV = versions.split(",");
        for (VersionController vc : versionList) {
            int status = vc.getServerStatus();
            if(status!=VersionController.SERVICE_API_ABNORMAL&&status!=VersionController.SERVICE_ACCESS_ABNORMAL){
                String[] now = new String[5];
                int flag = 0;
                now[VersionController.ZZD_VERSION_IND-3]=vc.getZzdVersion();
                now[VersionController.ENCODER_VERSION_IND-3]=vc.getEncoderVersion();
                now[VersionController.MERGE_TOOL_VERSION_IND-3]=vc.getMergeToolVersion();
                now[VersionController.MERGE_SERVICE_VERSION_IND-3]=vc.getMergeServiceVersion();
                now[VersionController.PRECISION_CUT_TOOL_VERSION_IND-3]=vc.getPrecisionCutToolVersion();
                for(int i=0;i<VersionController.VERSION_NUM;i++){
                    if(!now[i].equals(mV[i])){
                        flag=1;
                        break;
                    }
                }
                if(flag==0){
                    vc.setServerStatus(VersionController.SERVICE_NORMAL);
                }else{
                    vc.setServerStatus(VersionController.DIFFERENT_VERSION);
                }

                insertOrUpdate(vc);

            }
        }

        return 1;
    }

}
